/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bsc.bscpb;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileLock;

/**
 *
 * @author Administrator
 */
public class LockThread extends Thread {

    boolean islock = false;
    public boolean getreturn() {
        return islock;
    }
    
    public void setreturn(boolean islock){
        this.islock = islock;
    }

    @Override
    public void run() {
        String userhome = System.getProperty("user.home");


        if (userhome != null) {
            File bsclock = new File(userhome + "/BscLock");
            if (!bsclock.exists()) {
                try {
                    System.out.println("文件不存在");
                    bsclock.createNewFile();
                    FileOutputStream fous = new FileOutputStream(bsclock);
                    FileLock lock = fous.getChannel().tryLock();
                    System.out.println(lock);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                setreturn(false);
            } else {
                try {
                    System.out.println("文件存在");
                    FileOutputStream fous = new FileOutputStream(bsclock);
                    FileLock lock = fous.getChannel().tryLock();
                    System.out.println(lock);
                    if (lock != null) {
                        setreturn(false);
                    } else {
                        setreturn(true);
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }


        if(getreturn()){
            System.out.println("*****************系统已运行*****************");
            System.exit(0);
        }
        while (!islock) {
        }
    }
}
